package com.yami.shop.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Objects;

@RestController
@RequestMapping("/userRegister")
@Tag(name = "用户注册通过code获取openid")
@AllArgsConstructor
public class TestController {

        private static final String APPID = "wxe9f0c5605b4e88d8";// 微信应用唯一标识
        private static final String SECRET = "dc36864cfb0335e8f971936283cb2fff";

        public void main(String code) {

            JSONObject jsonObject = code2sessionKey(code);

            String openId = jsonObject.getString("openid");// 用户唯一标识

            String session_key = jsonObject.getString("session_key");// 密钥

            // 满足UnionID下发条件的情况下，返回
            String unionId = jsonObject.getString("unionid");

        }

        /**
         * 发送请求用code换取sessionKey和相关信息
         *
         * @param code
         * @return
         */
        @RequestMapping("/getOpenid")

        public static JSONObject code2sessionKey(String code) {
            String stringToken = String.format(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+"&secret="+SECRET+"&js_code="+code+"&grant_type=authorization_code",
                    APPID, SECRET, code);
            String response = httpsRequestToString(stringToken, "GET", null);
            return JSON.parseObject(response);
        }

        /**
         * 发送https请求
         *
         * @param path
         * @param method
         * @param body
         * @return
         */
        public static String httpsRequestToString(String path, String method, String body) {
            if (path == null || method == null) {
                return null;
            }
            String response = null;
            InputStream inputStream = null;
            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;
            HttpsURLConnection conn = null;
            try {
                // 创建SSLConrext对象，并使用我们指定的信任管理器初始化
                SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
                TrustManager[] tm = { new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                } };
                sslContext.init(null, tm, new java.security.SecureRandom());

                // 从上面对象中得到SSLSocketFactory
                SSLSocketFactory ssf = sslContext.getSocketFactory();

                URL url = new URL(path);
                conn = (HttpsURLConnection) url.openConnection();
                conn.setSSLSocketFactory(ssf);

                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches(false);

                // 设置请求方式（get|post）
                conn.setRequestMethod(method);

                // 有数据提交时
                if (null != body) {
                    OutputStream outputStream = conn.getOutputStream();
                    outputStream.write(body.getBytes("UTF-8"));
                    outputStream.close();
                }

                // 将返回的输入流转换成字符串
                inputStream = conn.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                StringBuilder buffer = new StringBuilder();
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }

                response = buffer.toString();
            } catch (Exception e) {

            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
                try {
                    Objects.requireNonNull(bufferedReader).close();
                    Objects.requireNonNull(inputStreamReader).close();
                    inputStream.close();
                } catch (IOException execption) {

                }
            }
            return response;
        }
}
